#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: categories.py
@contact: zwb15083976291@163.com
@time: 2021/11/16
"""
from django.db.models import Q
from rest_framework import serializers
from common.models import BlogCategorie, BlogArticle
from utils.serializers.serializer import SpecifySerializeFieldModelSerializer, UpdateBaseSerializeMethodMixin


class CategoriesSerializer(UpdateBaseSerializeMethodMixin, SpecifySerializeFieldModelSerializer):
    id = serializers.IntegerField()

    class Meta:
        model = BlogCategorie
        fields = '__all__'


class PostCategoriesSerializer(CategoriesSerializer):

    def validate_categorie_name(self, value):
        if BlogCategorie.objects.filter(categorie_name=value).first():
            raise serializers.ValidationError("分类已存在")

        return value


class PutCategoriesSerializer(PostCategoriesSerializer):

    def validate_id(self, value):
        categorie = BlogCategorie.objects.filter(id=value).first()
        if not categorie:
            raise serializers.ValidationError('分类不存在')
        self.context["categorie_obj"] = categorie
        return value


class DeleteCategoriesSerializer(CategoriesSerializer):

    def validate_id(self, value):
        categorie = BlogCategorie.objects.filter(id=value).first()
        if not categorie:
            raise serializers.ValidationError('分类不存在')
        if categorie.categorie_count != 0 or BlogArticle.objects.filter(categorie=value).count() != 0:
            raise serializers.ValidationError("删除失败,存在文章相关联")
        return value


class BatchDeleteCategoriesSerializer(CategoriesSerializer):
    ids = serializers.ListField(label="文章id")

    def validate_ids(self, value):
        query_set = BlogCategorie.objects.filter(Q(id__in=set(value)))
        result = set(value) - set(query_set.values_list('id', flat=True))
        if result:
            raise serializers.ValidationError(f"删除失败!,{result} 不存在")

        query_set = BlogCategorie.objects.filter(Q(id__in=set(value)) & Q(categorie_count=0))
        result = set(value) - set(query_set.values_list('id', flat=True))
        if result:
            raise serializers.ValidationError(f"删除失败!,{result}存在文章相关联")
        return value
